package com.redsun.smallworld.service;

/**
 * Created by zhebinwang on 2017/7/20.
 */

//
// a Lisntener class that implements DiscoveryListener
// From a source code published in Benhui.net claimes that
// Impronto prefers to have a Lisntener class.
// conn: RFCOMM
//

import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;

public class RFListener implements DiscoveryListener
{
    private static RemoteDevice remote;
    private static ServiceRecord first;

    public RemoteDevice getDevFound() {
        return remote;
    }

    public void deviceDiscovered(RemoteDevice rt, DeviceClass cod) {
        remote = rt;
        System.out.println("A Remote Device Found:");
        System.out.println("Address: " + rt.getBluetoothAddress());
        try {
            System.out.println("   Name: " + rt.getFriendlyName(true));
        } catch (IOException e) {}
    }

    public void inquiryCompleted(int distype) {
        if(distype == INQUIRY_TERMINATED)
            System.out.println("Application Terminated");
        else if(distype == INQUIRY_COMPLETED)
            System.out.println("Inquiry Completed");
        else
            System.out.println("ERROR: Inquiry aborted");
    }

    // 當裝置從遠端的藍芽裝置發現該裝置上有服務的時候，會先呼叫
    // servicesDiscovered() 然後 serviceSearchCompleted()
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        first = servRecord[0];

        // 從 service record 來取得 url
        String url = first.getConnectionURL(first.NOAUTHENTICATE_NOENCRYPT, false);
        try {
            // 與 server 建立連線
            StreamConnection conn = (StreamConnection) Connector.open(url);

            String message = "What time is it now?";
            InputStream is = conn.openInputStream();
            OutputStream os = conn.openOutputStream();
            byte[] rbuf = new byte[100];
            os.write(message.getBytes());
            is.read(rbuf);
            System.out.println(new String(rbuf));
            is.close();
            os.close();
            conn.close();
        } catch (Exception e) {
            System.out.println("ERROR: connection error");
        }
    }

    public void serviceSearchCompleted(int transID, int respCode) {
        // 依照 respCode 來了解 serviceSearch 的結果
        if(respCode == SERVICE_SEARCH_COMPLETED)
            System.out.println("Services successfully located");
        else if(respCode == SERVICE_SEARCH_TERMINATED)
            System.out.println("Service inquiry was cancelled");
        else if(respCode == SERVICE_SEARCH_DEVICE_NOT_REACHABLE)
            System.out.println("Service connection cannot be established");
        else if(respCode == SERVICE_SEARCH_NO_RECORDS)
            System.out.println("No service found");
        else
            System.out.println("ERROR: service inquiry failed");
    }
}
